package main

import (
	"encoding/json"
	"fmt"
	"github.com/nats-io/go-nats"
	"log"
)

const (
	//url   = "nats://192.168.3.125:4222"
	ServerNatUrl          = nats.DefaultURL
	ServerProductInfoSubj = "product_info_subj"
)

var (
	encodeConnServer *nats.EncodedConn
	connServer       *nats.Conn
	errServer        error
)

func init() {
	if connServer, errServer = nats.Connect(ServerNatUrl); errServer != nil {
		fmt.Println("初始化错误：", errServer)
	} else {
		if encodeConnServer, errServer = nats.NewEncodedConn(connServer, nats.JSON_ENCODER); errServer != nil {
			if errServer != nil {
				log.Fatal("初始化encodeConn失败：", errServer)
			}
		}
	}
}

func main() {
	ServerInfoBySubj()
}

/*
服务端的启动
./main -port=servive -servername=C -group=test -subj=weather
*/

func ServerInfoBySubj() {
	var (
		servername = "nat_server_test"
		queueGroup = ""
		subj       = ServerProductInfoSubj
	)
	// 推送基础包数据
	ServerListen(servername, queueGroup, subj)
}

func ServerListen(servername, queueGroup, subj string) {
	log.Println(servername, queueGroup, subj)
	startService(subj, servername, queueGroup)
	_ = connServer.Flush()
	select {}
}

// receive message
func startService(subj, name, queue string) {
	go asyncByRequest(encodeConnServer, subj, name, queue)
}

type BaseData1 struct {
	Name string
	Age  int64
	High int64
}

func asyncByRequest(nc *nats.EncodedConn, subj, name, queue string) {
	replyMsg := name + " Received2 a msg"
	if queue == "" {
		//bd := nats.Msg{
		//	Subject:subj,
		//	Data:[]byte("hello"),
		//}
		bd := BaseData1{
			Name: "hello",
		}
		replyMsg, _ := json.Marshal(bd)
		_, errServer = nc.Subscribe(subj, func(msg *nats.Msg) {
			errServer = connServer.Publish(msg.Reply, []byte(replyMsg))
			fmt.Println(name, "成功收到的消息为:", string(msg.Data))
			fmt.Println(name, "成功收到消息后回馈的消息为:", bd)
		})
	} else {
		_, errServer = nc.QueueSubscribe(subj, queue, func(msg *nats.Msg) {
			errServer = connServer.Publish(msg.Reply, []byte(replyMsg))
			fmt.Println(name, "成功收到的queue消息为: ", string(msg.Data))
		})
	}

	if errServer != nil {
		log.Fatal("监听异常：", errServer)
	}
}
